<?php

namespace App\Http\Controllers\Auth\Owner;

use DB;
use Log;
use Illuminate\Support\Str;
use Common\Models\User\User;
use Illuminate\Http\Request;
use Common\Models\User\UserQQ;
use Common\Models\User\UserWeibo;
use Common\Models\User\UserQQInfo;
use Common\Models\User\UserWechat;
use Illuminate\Support\Facades\Hash;
use Common\Models\User\UserWeiboInfo;
use Common\Services\User\UserService;
use Common\Models\User\UserWechatInfo;
use Reheat\Laravel\Facades\ApiResponse;
use Common\Services\User\UserDeviceService;
use Common\Resources\Auth\AuthorizationResource;

/**
 * SocialiteController.
 *
 * @license [http://www.85do.com] [杭州永奥网络科技有限公司]
 * @copyright Copyright (c) 2018-2026 Hangzhou Yongao Technology Co., Ltd. All rights reserved.
 */
class SocialiteController extends Controller
{
    /**
     * QQ登录.
     */
    public function qq(Request $request)
    {
        // 数据验证
        $this->validate($request, [
            'avatar'   => 'required|max:255',
            'openid'   => 'required|max:128',
            'nickname' => 'required|max:128',

            'pf'           => 'max:233',
            'pfkey'        => 'max:233',
            'unionid'      => 'max:128',
            'pay_token'    => 'max:255',
            'expires_in'   => 'integer',
            'access_token' => 'max:255',
        ], [
            'avatar.required'   => '请输入昵称头像地址',
            'avatar.max'        => '头像地址太长了',
            'openid.required'   => '请传入openid',
            'openid.max'        => 'openid太长了',
            'nickname.required' => '请输入昵称',
            'nickname.max'      => '昵称太长了',

            'pf.max'             => '太长了',
            'pfkey.max'          => '太长了',
            'unionid.max'        => '太长了',
            'pay_token.max'      => '太长了',
            'expires_in.integer' => '请传入正确的过期时间戳',
            'access_token.max'   => '太长了',
        ]);

        // 数据获取
        $avatar   = $request->post('avatar'); //required
        $openid   = $request->post('openid'); //required
        $nickname = $request->post('nickname'); //required

        $pf           = $request->post('pf', '');
        $pfkey        = $request->post('pfkey', '');
        $unionid      = $request->post('unionid', '');
        $pay_token    = $request->post('pay_token', '');
        $expires_in   = $request->post('expires_in', '');
        $access_token = $request->post('access_token', '');

        /*
         |--------------------------------------------------------------------------
         | 用户已经存在
         |--------------------------------------------------------------------------
         */
        /** @var UserQQ $userQQ */
        $userQQ = UserQQ::where('openid', $openid)->first();
        if ($userQQ) {
            // 获取系统用户
            /** @var User $user */
            $user = $userQQ->user;
            if (is_null($user)) {
                //记录登录失败日志
                Log::error("QQ  Login failed：{$openid}");

                return ApiResponse::error('登录失败');
            }

            // 验证禁用状态
            if ($user->isDisable()) {
                return ApiResponse::error('账号已禁用');
            }

            // 获取额外信息
            /** @var UserQQInfo $userInfo */
            $userInfo = $userQQ->info;
            if (is_null($userInfo)) {
                //记录登录失败日志
                Log::error("QQ Info Login failed：{$openid}");

                return ApiResponse::error('登录失败');
            }

            //同步更新用户重要信息，保持最新
            $user->nickname = $nickname;
            $user->avatar   = $avatar;
            $user->update();

            //同步更新到用户信息
            $userInfo->nickname  = $nickname;
            $userInfo->figureurl = $avatar;
            $userInfo->update();

            // 生成token并合并输出
            return ApiResponse::data(new AuthorizationResource($user));
        }

        /*
         |--------------------------------------------------------------------------
         | 用户第一次登录
         |--------------------------------------------------------------------------
         */
        DB::beginTransaction();
        try {
            $user           = new User();
            $user->username = 'user_'.time();
            $user->salt     = Str::random(6);
            $user->password = Hash::make(md5(Str::random(12).$user->salt));
            $user->nickname = $nickname;
            $user->avatar   = $avatar;
            $user->save();

            $userQQ               = new UserQQ();
            $userQQ->user_id      = $user->id;
            $userQQ->pf           = $pf;
            $userQQ->pfkey        = $pfkey;
            $userQQ->openid       = $openid;
            $userQQ->unionid      = $unionid;
            $userQQ->pay_token    = $pay_token;
            $userQQ->expires_in   = $expires_in;
            $userQQ->access_token = $access_token;
            $userQQ->save();

            $userInfo            = new UserQQInfo();
            $userInfo->user_id   = $user->id;
            $userInfo->nickname  = $nickname;
            $userInfo->figureurl = $avatar;
            $userInfo->save();

            // 初始话用户信息子表
            UserService::init($user);

            //保存用户设备参数
            UserDeviceService::save($user, $request);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            Log::error('QQ登录注册事务操作失败： '.$e->getMessage());

            return ApiResponse::error('注册失败!');
        }

        // 生成token并合并输出
        return ApiResponse::data(new AuthorizationResource($user));
    }

    /**
     * 微信登录.
     */
    public function wechat(Request $request)
    {
        // 数据验证
        $this->validate($request, [
            'avatar'   => 'required|max:255',
            'openid'   => 'required|max:128',
            'nickname' => 'required|max:128',

            'unionid'       => 'max:128',
            'expires_in'    => 'integer',
            'access_token'  => 'max:255',
            'refresh_token' => 'max:255',
        ], [
            'avatar.required'   => '请输入昵称头像地址',
            'avatar.max'        => '头像地址太长了',
            'openid.required'   => '请传入openid',
            'openid.max'        => 'openid太长了',
            'nickname.required' => '请输入昵称',
            'nickname.max'      => '昵称太长了',

            'unionid.max'        => '太长了',
            'expires_in.integer' => '请传入正确的过期时间戳',
            'access_token.max'   => '太长了',
            'refresh_token.max'  => '太长了',
        ]);

        // 数据获取
        $avatar   = $request->post('avatar'); //required
        $openid   = $request->post('openid'); //required
        $nickname = $request->post('nickname'); //required

        $unionid       = $request->post('unionid', '');
        $expires_in    = $request->post('expires_in', '');
        $access_token  = $request->post('access_token', '');
        $refresh_token = $request->post('refresh_token', '');

        /*
         |--------------------------------------------------------------------------
         | 用户已经存在
         |--------------------------------------------------------------------------
         */
        /** @var UserQQ $userQQ */
        $userWechat = UserWechat::where('openid', $openid)->first();
        if ($userWechat) {
            // 获取系统用户
            /** @var User $user */
            $user = $userWechat->user;
            if (is_null($user)) {
                //记录登录失败日志
                Log::error("Wechat Login failed：{$openid}");

                return ApiResponse::error('登录失败');
            }

            // 验证禁用状态
            if ($user->isDisable()) {
                return ApiResponse::error('账号已禁用');
            }

            // 获取额外信息
            /** @var UserWechatInfo $userWechatInfo */
            $userWechatInfo = $userWechat->info;
            if (is_null($userWechatInfo)) {
                //记录登录失败日志
                Log::error("Wechat Info Login failed：{$openid}");

                return ApiResponse::error('登录失败');
            }

            //同步更新用户重要信息，保持最新
            $user->nickname = $nickname;
            $user->avatar   = $avatar;
            $user->update();

            //同步更新到微信用户信息
            $userWechatInfo->nickname   = $nickname;
            $userWechatInfo->headimgurl = $avatar;
            $userWechatInfo->update();

            // 生成token并合并输出
            return ApiResponse::data(new AuthorizationResource($user));
        }

        /*
         |--------------------------------------------------------------------------
         | 用户第一次登录
         |--------------------------------------------------------------------------
         */
        DB::beginTransaction();
        try {
            $user           = new User();
            $user->username = 'user_'.time();
            $user->salt     = Str::random(6);
            $user->password = Hash::make(md5(Str::random(12).$user->salt));
            $user->nickname = $nickname;
            $user->avatar   = $avatar;
            $user->save();

            $userWechat                = new UserWechat();
            $userWechat->user_id       = $user->id;
            $userWechat->openid        = $openid;
            $userWechat->unionid       = $unionid;
            $userWechat->expires_in    = $expires_in;
            $userWechat->access_token  = $access_token;
            $userWechat->refresh_token = $refresh_token;
            $userWechat->save();

            $userWechatInfo             = new UserWechatInfo();
            $userWechatInfo->user_id    = $user->id;
            $userWechatInfo->nickname   = $nickname;
            $userWechatInfo->headimgurl = $avatar;
            $userWechatInfo->save();

            // 初始话用户信息子表
            UserService::init($user);

            //保存用户设备参数
            UserDeviceService::save($user, $request);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            Log::error('微信登录注册事务操作失败： '.$e->getMessage());

            return ApiResponse::error('注册失败!');
        }

        // 生成token并合并输出
        return ApiResponse::data(new AuthorizationResource($user));
    }

    /**
     * 微博登录.
     */
    public function weibo(Request $request)
    {
        // 数据验证
        $this->validate($request, [
            'uid'      => 'required|max:128',
            'avatar'   => 'required|max:255',
            'nickname' => 'required|max:128',

            'expires_in'   => 'integer',
            'access_token' => 'max:255',
        ], [
            'uid.required'      => '请传入uid',
            'uid.max'           => 'uid太长了',
            'avatar.required'   => '请输入昵称头像地址',
            'avatar.max'        => '头像地址太长了',
            'nickname.required' => '请输入昵称',
            'nickname.max'      => '昵称太长了',

            'expires_in.integer' => '请传入正确的过期时间戳',
            'access_token.max'   => '太长了',
        ]);

        // 数据获取
        $uid      = $request->post('uid'); //required
        $avatar   = $request->post('avatar'); //required
        $nickname = $request->post('nickname'); //required

        $expires_in   = $request->post('expires_in', '');
        $access_token = $request->post('access_token', '');
        /*
         |--------------------------------------------------------------------------
         | 用户已经存在
         |--------------------------------------------------------------------------
         */
        /** @var UserWeibo $userWeibo */
        $userWeibo = UserWeibo::where('uid', $uid)->first();
        if ($userWeibo) {
            // 获取系统用户
            /** @var User $user */
            $user = $userWeibo->user;
            if (is_null($user)) {
                //记录登录失败日志
                Log::error("Weibo Login failed：{$uid}");

                return ApiResponse::error('登录失败');
            }

            // 验证禁用状态
            if ($user->isDisable()) {
                return ApiResponse::error('账号已禁用');
            }

            // 获取额外信息
            /** @var UserWeiboInfo $userWeiboInfo */
            $userWeiboInfo = $userWeibo->info;
            if (is_null($userWeiboInfo)) {
                //记录登录失败日志
                Log::error("Weibo Info Login failed：{$uid}");

                return ApiResponse::error('登录失败');
            }

            //同步更新用户重要信息，保持最新
            $user->nickname = $nickname;
            $user->avatar   = $avatar;
            $user->update();

            //同步更新到微信用户信息
            $userWeiboInfo->screen_name       = $nickname;
            $userWeiboInfo->profile_image_url = $avatar;
            $userWeiboInfo->update();

            // 生成token并合并输出
            return ApiResponse::data(new AuthorizationResource($user));
        }

        /*
         |--------------------------------------------------------------------------
         | 用户第一次登录
         |--------------------------------------------------------------------------
         */
        DB::beginTransaction();
        try {
            $user           = new User();
            $user->username = 'user_'.time();
            $user->salt     = Str::random(6);
            $user->password = Hash::make(md5(Str::random(12).$user->salt));
            $user->nickname = $nickname;
            $user->avatar   = $avatar;
            $user->save();

            $userWeibo               = new UserWeibo();
            $userWeibo->user_id      = $user->id;
            $userWeibo->uid          = $uid;
            $userWeibo->expires_in   = $expires_in;
            $userWeibo->access_token = $access_token;
            $userWeibo->save();

            $userWeiboInfo                    = new UserWeiboInfo();
            $userWeiboInfo->user_id           = $user->id;
            $userWeiboInfo->screen_name       = $nickname;
            $userWeiboInfo->profile_image_url = $avatar;
            $userWeiboInfo->save();

            // 初始话用户信息子表
            UserService::init($user);

            //保存用户设备参数
            UserDeviceService::save($user, $request);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            Log::error('微博登录注册事务操作失败： '.$e->getMessage());

            return ApiResponse::error('注册失败!');
        }

        return ApiResponse::data(new AuthorizationResource($user));
    }
}
